<template>
  <el-form-item label="售价" :rules="rules.payOfCurrencyCount" prop="payOfCurrencyCount">
    <div style="display: flex;flex-wrap: nowrap;">
      <el-input v-model="payOfCurrencyCount" style="width:auto">
        <template #append>
          积分
        </template>
      </el-input>
      <div style="width: 10px"></div>
      <el-form-item :rules="rules.payPrice" prop="payPrice">
        <el-input v-model="payPrice">
          <template #append>
            元
          </template>
        </el-input>
      </el-form-item>
    </div>
  </el-form-item>
</template>

<script setup lang="ts">
import { positiveInteger_0, positiveNumber_decimal$2 } from "@/utils/commonRegexp";

const props = defineProps<{
  modelValue1?: number | null | string, // payOfCurrencyCount
  modelValue2?: number | null | string, // payPrice
}>()
const modelValue2Ref = toRef(props, 'modelValue2')

const emits = defineEmits(['update:model-value1', 'update:model-value2'])

const payOfCurrencyCount = computed({
  get() {
    return props.modelValue1
  },
  set(newValue) {
    emits('update:model-value1', newValue)
  }
})

const payPrice = ref()
watch(payPrice, (newValue) => {
  emits("update:model-value2", isNaN(Number(newValue)) ? newValue : parseInt((Number(newValue) * 100).toFixed(2).slice(0, -3)))
})
watch(modelValue2Ref, (newValue) => {
  payPrice.value = isNaN(Number(newValue)) ? newValue : Number(newValue) / 100
})

onMounted(() => {
  payPrice.value = isNaN(Number(modelValue2Ref.value)) ? modelValue2Ref.value : Number(modelValue2Ref.value) / 100
})

const rules = {
  payOfCurrencyCount: [{
    trigger: 'blur',
    required: true,
    validator(rule: any, val: any, callback: any) {
      console.log('sale price validator')
      if (!positiveInteger_0.test('' + payOfCurrencyCount.value)) {
        callback(`请输入售价（积分），且只能为0或正整数`)
        return
      }

      if (Number(payOfCurrencyCount.value) > 9999999999) {
        callback(`请输入售价（积分），超过上限【99,9999,9999】`)
        return
      }

      callback()
    }
  }],
  payPrice: [
    {
      trigger: 'blur',
      required: true,
      validator(rule: any, val: any, callback: any) {
        console.log('sale price validator')
        if (!positiveNumber_decimal$2.test('' + payPrice.value)) {
          callback(`售价（现金）不正确，不能为负数且仅保留2位小数`)
          return
        }

        if (Number(payPrice.value) > 9999999999) {
          callback(`售价（现金），超过上限【99,9999,9999】`)
          return
        }

        callback()
      }
    }]
}
</script>
